package com.benchmark.springboot.config;

import com.benchmark.springboot.component.RestTemplateClient;
import com.power.common.net.SSLSocketFactoryBuilder;
import com.power.common.net.TrustAnyTrustManager;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;

import javax.annotation.Resource;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.concurrent.TimeUnit;

/**
 * @author yu 2018/12/20.
 */
@Configuration
public class RestTemplateClientConfig {

    @Resource
    private Environment env;

    /**
     * 兼容http和https
     *
     * @return
     * @throws Exception
     */
    @Bean
    public RestTemplateClient restTemplateClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.sslSocketFactory(SSLSocketFactoryBuilder.getSslSocketFactory(), new TrustAnyTrustManager())
                .connectionPool(pool())
                .retryOnConnectionFailure(false)
                .hostnameVerifier((s, sslSession) -> true)
                .connectTimeout(NumberUtils.toInt(env.getProperty("http.rest.connectTimeout"), 1000), TimeUnit.SECONDS)
                .readTimeout(NumberUtils.toInt(env.getProperty("http.rest.readTimeout"), 1000), TimeUnit.SECONDS)
                .writeTimeout(NumberUtils.toInt(env.getProperty("http.rest.writeTimeout"), 1000), TimeUnit.SECONDS);
        OkHttpClient okHttpClient = builder.build();
        OkHttp3ClientHttpRequestFactory httpClient = new OkHttp3ClientHttpRequestFactory(okHttpClient);
        return new RestTemplateClient(httpClient);
    }


    /**
     * 创建代理
     *
     * @return
     */
    @Bean
    public Proxy proxy() {
        String proxyHost = env.getProperty("http.proxy.host", "127.0.0.1");
        final int proxyPortNum = NumberUtils.toInt(env.getProperty("http.proxy.port", "80"));
        InetSocketAddress address = new InetSocketAddress(proxyHost, proxyPortNum);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
        return proxy;
    }


    /**
     * 创建连接池
     *
     * @return
     */
    @Bean
    public ConnectionPool pool() {
        int maxIdleConnection = NumberUtils.toInt(env.getProperty("okttp.maxIdleConnection"), 50);
        long keepAliveDuration = NumberUtils.toLong(env.getProperty("okhttp.keepAliveDuration"), 10);
        return new ConnectionPool(maxIdleConnection, keepAliveDuration, TimeUnit.MINUTES);
    }

}
